'use strict';
module.exports = {
	/**
	 * @url client/baidu-ai/pub/fix-live-tool 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		// 用户信息
    const db = uniCloud.database();
    let total_fee = 6
    let user_id = '653b78678b0da47be1f71762'
		let userRes = await db.collection('uni-id-users').where({ _id: user_id }).get();
		let userInfo = userRes.data[0];
		console.log(`用户信息：${JSON.stringify(userInfo)}`)
		
		console.log(`inviter_uid：${userInfo.inviter_uid}`)
		// 邀请分成
		let { inviter_uid = '' } = userInfo
		let inviterUserRes = await db.collection('uni-id-users').where({ _id: inviter_uid }).get();
		let inviterUserInfo = inviterUserRes.data[0];
		if (inviterUserInfo) {
			console.log(`inviter_uid: ${inviter_uid}----`)
			let increMoney = parseInt(config.saleRatio * total_fee)
			console.log(`increMoney: ${increMoney}----`)
			await db.collection("uni-id-users").doc(inviterUserInfo._id).update({
			  balance: ([null,undefined].includes(inviterUserInfo.balance) ? 0 : inviterUserInfo.balance) + increMoney,
			  total_revenue: ([null,undefined].includes(inviterUserInfo.total_revenue) ? 0 : inviterUserInfo.total_revenue) + increMoney
			});
			await db.collection("ai-earning-detail").add({
			  user_id: inviterUserInfo._id,
			  amount: increMoney,
			  change_class: 1,
			  change_scene: 1,
			  created_at: new Date().getTime()
			})
		}
		
		// 三级分佣，查找上级邀请者
		let parent_inviter_uid = inviterUserInfo.inviter_uid
		if (parent_inviter_uid) {
		  let parentInviterUserRes = await db.collection('uni-id-users').where({ _id: parent_inviter_uid }).get();
		  let parentInviterUserInfo = parentInviterUserRes.data[0];
		  if (parentInviterUserInfo) {
		    console.log(`parent_inviter_uid: ${parent_inviter_uid}----`)
		    let parentIncreMoney = parseInt(config.secondaryRatio * total_fee)
		    console.log(`parent increMoney: ${parentIncreMoney}----`)
		    await db.collection("uni-id-users").doc(parentInviterUserInfo._id).update({
		      balance: ([null,undefined].includes(parentInviterUserInfo.balance) ? 0 : parentInviterUserInfo.balance) + parentIncreMoney,
		      total_revenue: ([null,undefined].includes(parentInviterUserInfo.total_revenue) ? 0 : parentInviterUserInfo.total_revenue) + parentIncreMoney
		    });
		    await db.collection("ai-earning-detail").add({
		      user_id: parentInviterUserInfo._id,
		      amount: parentIncreMoney,
		      change_class: 1,
		      change_scene: 2,
		      created_at: new Date().getTime()
		    })
		  }
		}
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}
